package com.wanli.agent.homepage;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseFragment;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.BankCardBean;
import com.wanli.agent.bean.EBankStoreDataContacts;
import com.wanli.agent.bean.EBankStoreDataInfo;
import com.wanli.agent.bean.ImageBean;
import com.wanli.agent.bean.StoreDeatilsBean;
import com.wanli.agent.dialog.ChooseBankDialog;
import com.wanli.agent.event.ChooseBankEvent;
import com.wanli.agent.event.StoreDataEvent;
import com.wanli.agent.event.StoreNextEvent;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.utils.Base64BitmapUtil;
import com.wanli.agent.utils.GlideEngine;
import com.wanli.agent.utils.GlideUtils;
import com.wanli.agent.utils.PermissionsManager;
import com.wanli.agent.utils.SPManager;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * 门店信息
 */
public class EBankStoreBankFragment extends BaseFragment {
    public static final String TITLE_TYPE = "type";
    public static final String MERCHANT_ID = "merchant_id";
    public static final String QUICK_INCOME = "quick_income";
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.ll_bank_name)
    LinearLayout llBankName;
    @BindView(R.id.view_end_time)
    View viewEndTime;
    @BindView(R.id.edit_bank_username)
    EditText editBankUsername;
    @BindView(R.id.edit_bank_mobile)
    EditText editBankMobile;
    @BindView(R.id.edit_bank_idNumber)
    EditText editBankIdNumber;
    @BindView(R.id.edit_bank_num)
    EditText editBankNum;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.ic_prcture_4)
    ImageView icPrcture4;
    @BindView(R.id.iv_picture_demo_4)
    ImageView ivPictureDemo4;

    private String type;
    private IHomePageModel homePageModel;
    private Gson mGson = new Gson();
    private StoreDeatilsBean.DataBean storeBean;
    private String merchant_id;
    private int quick_income;

    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private List<LocalMedia> mediaList = new ArrayList<>();
    private String imgPath4;
    private String prctureDemo4 = "https://wnb-dc.oss-cn-qingdao.aliyuncs.com/resources/yinhangkazhengmian.jpg";
    private String bankName;
    private String branchName;
    private String branch_city;
    private String branch_province;
    private String unionpay;
    private ArrayList<String> options4Items = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ebank_store_info, container, false);
        ButterKnife.bind(this, view);
        registerEventBus();
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getString(TITLE_TYPE);
            StoreDataEvent dataEvent = EventBus.getDefault().getStickyEvent(StoreDataEvent.class);
            if (dataEvent != null) {
                storeBean = dataEvent.getDataBean();
            }
            merchant_id = bundle.getString(MERCHANT_ID);
            quick_income = bundle.getInt(QUICK_INCOME);
        }
        initView();
        initData();
        return view;
    }

    private void initView() {
        permissionsManager = new PermissionsManager(mActivity);
        if ("1".equals(type)) {

        } else if ("2".equals(type)) {

        } else if ("3".equals(type)) {

        }

        GlideUtils.loadImage(mActivity, ivPictureDemo4, prctureDemo4);

        options4Items.add("个人账户");
        options4Items.add("公司账户");
    }


    public void initData() {
        homePageModel = new HomePageModelImpl();

        if (storeBean != null) {
            imgPath4 = storeBean.getBank_card_front_pic();
            if (!TextUtils.isEmpty(imgPath4)) {
                GlideUtils.loadImage(mActivity, icPrcture4, imgPath4);
            }
            bankName = storeBean.getBank();
            branchName = storeBean.getBranch();
            branch_province = storeBean.getBranch_province();
            branch_city = storeBean.getBranch_city();
            unionpay = storeBean.getUnionpay();

            tvBankName.setText(storeBean.getBranch());
            editBankUsername.setText(storeBean.getHolder());
            if (!TextUtils.isEmpty(storeBean.getHolder())) {
                editBankUsername.setSelection(storeBean.getHolder().length());
            }
            editBankMobile.setText(storeBean.getHolder_mobile());
            if (!TextUtils.isEmpty(storeBean.getHolder_mobile())) {
                editBankMobile.setSelection(storeBean.getHolder_mobile().length());
            }
            editBankIdNumber.setText(storeBean.getHolder_id_card_no());
            if (!TextUtils.isEmpty(storeBean.getHolder_id_card_no())) {
                editBankIdNumber.setSelection(storeBean.getHolder_id_card_no().length());
            }
            editBankNum.setText(storeBean.getBank_card_no());
            if (!TextUtils.isEmpty(storeBean.getBank_card_no())) {
                editBankNum.setSelection(storeBean.getBank_card_no().length());
            }
        }
    }

    @Subscribe
    public void onChooseBankEvent(ChooseBankEvent event) {

        tvBankName.setText(event.getBankBranch());
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            String name = editBankUsername.getText().toString();
            String mobile = editBankMobile.getText().toString();
            String idNumber = editBankIdNumber.getText().toString();
            EBankStoreDataContacts storeDataBasic = null;
            if (!TextUtils.isEmpty(SPManager.getInstance().getStoreBasic())) {
                storeDataBasic = mGson.fromJson(SPManager.getInstance().getStoreCompany(), EBankStoreDataContacts.class);
            }
            if (TextUtils.isEmpty(name) && storeDataBasic != null) {
                if (!TextUtils.isEmpty(storeDataBasic.getContact_name())) {
                    editBankUsername.setText(storeDataBasic.getContact_name());
                }
            }
            if (TextUtils.isEmpty(mobile) && storeDataBasic != null) {
                if (!TextUtils.isEmpty(storeDataBasic.getContact_mobile())) {
                    editBankMobile.setText(storeDataBasic.getContact_mobile());
                }
            }
            if (TextUtils.isEmpty(idNumber) && storeDataBasic != null) {
                if (!TextUtils.isEmpty(storeDataBasic.getLegal_id_card_no())) {
                    editBankIdNumber.setText(storeDataBasic.getLegal_id_card_no());
                }
            }
        }
        if (isViewCreated && !isVisibleToUser) {
            Log.d("---", "333333333333333333333333");
            EBankStoreDataInfo dataInfo = new EBankStoreDataInfo();
            dataInfo.setBank(bankName);
            dataInfo.setBranch(branchName);
            dataInfo.setBranch_province(branch_province);
            dataInfo.setBranch_city(branch_city);
            dataInfo.setUnionpay(unionpay);
            dataInfo.setHolder(editBankUsername.getText().toString());
            dataInfo.setHolder_mobile(editBankMobile.getText().toString());
            dataInfo.setHolder_id_card_no(editBankIdNumber.getText().toString());
            dataInfo.setBank_card_no(editBankNum.getText().toString());
            dataInfo.setBank_card_front_pic(imgPath4);

            SPManager.getInstance().saveStoreInfo(mGson.toJson(dataInfo));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @OnClick({R.id.ic_prcture_4, R.id.ll_bank_name, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_prcture_4:
                showPictureSelectorDialog();
                break;
            case R.id.ll_bank_name:
//                skipToActivity(ChooseBankActivity.class);
                ChooseBankDialog dialog = ChooseBankDialog.newInstance(branch_province, branch_city, bankName, branchName, unionpay);
                dialog.show(getChildFragmentManager(), "dialog");
                dialog.setOnCallBackListener((provience, city, bank, branchBank, code) -> {
                    bankName = bank;
                    branchName = branchBank;
                    branch_province = provience;
                    branch_city = city;
                    unionpay = code;
                    tvBankName.setText(branchName);
                });
                break;
            case R.id.tv_commit:
                EventBus.getDefault().post(new StoreNextEvent(3));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> mediaList = PictureSelector.obtainMultipleResult(data);
                    if (mediaList.size() > 0) {
                        String imgPath = mediaList.get(0).getCompressPath();
                        requestUploadFile(imgPath);
                    }
                    break;
            }
        }

    }

    /**
     * 上传图片
     */
    public void requestUploadFile(String imgPath) {
        ViewLoading.showProgress(mActivity, "上传中......");
        Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
        String file = Base64BitmapUtil.bitmapToBase64(bitmap);
        homePageModel.requestUploadFile("store", file, new DataCallBack<ImageBean>() {
            @Override
            public void onSuccessful(ImageBean bean) {
                if (isDestroy()) {
                    return;
                }
                ToastUtil.showShort("上传成功");
                imgPath4 = bean.getData();
                GlideUtils.loadImage(mActivity, icPrcture4, imgPath);
                requestAliBankCard(bean.getData());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAliBankCard(String imgPath) {
        homePageModel.requestAliBankCard(imgPath, new DataCallBack<BankCardBean>() {
            @Override
            public void onSuccessful(BankCardBean bean) {
                if (bean.getData() != null && bean.getData().isSuccess()) {
                    ToastUtil.showShort("识别成功");
                    editBankNum.setText(bean.getData().getCard_num());
                    if (!TextUtils.isEmpty(bean.getData().getCard_num())) {
                        editBankNum.setSelection(bean.getData().getCard_num().length());
                    }
                    bankName = bean.getData().getBank_name();
                } else {
                    ToastUtil.showShort("识别失败，请输入");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(EBankStoreBankFragment.this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(EBankStoreBankFragment.this)//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {
            if (openType == 0) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else if (openType == 1) {
                openCamera();
                cancelPictureDialog();
            }
        }
    }
}
